package com.webbei.Backstage.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.wabbei.friendcenter.action.ReNameUtil;
import com.webbei.Backstage.service.BackstateSer;
import com.webbei.pojo.Cartypes;

public class NewCartypesAction {
		private int carseriesid;
		private BackstateSer bao;
		private File swfupload;
		private String swfuploadFileName;
		public String execute(){
			System.out.println(carseriesid+":"+swfuploadFileName);
			boolean b = bao.checkCartypeByName(swfuploadFileName);
			if(b){
				String ext =fileExt(swfuploadFileName);
				String NewNameFile=ReNameUtil.GetNewName()+ext;
				System.out.println(NewNameFile);
				copyFile(swfupload,NewNameFile);//send file
				Cartypes cartype=new Cartypes();
				cartype.setSeriesId(carseriesid);
				cartype.setTypesPic(NewNameFile);
				cartype.setTypesName(swfuploadFileName);
				int j=bao.insertNewCarTypes(cartype);
				if(j==1){
					System.out.println("insert CarTypes success");
				}else{
					System.out.println("insert CarTypes fails");
					return null;
				}
				System.out.println("insert is ok");
			}
			return null;
		}
		
		public BackstateSer getBao() {
			return bao;
		}

		public void setBao(BackstateSer bao) {
			this.bao = bao;
		}

		public File getSwfupload() {
			return swfupload;
		}

		public void setSwfupload(File swfupload) {
			this.swfupload = swfupload;
		}

		public String getSwfuploadFileName() {
			return swfuploadFileName;
		}

		public void setSwfuploadFileName(String swfuploadFileName) {
			this.swfuploadFileName = swfuploadFileName;
		}

		public int getCarseriesid() {
			return carseriesid;
		}

		public void setCarseriesid(int carseriesid) {
			this.carseriesid = carseriesid;
		}
		public boolean copyFile(File f,String fName){
			boolean b=true;
			if(f!=null){
					String realPath=ServletActionContext.getServletContext().getRealPath("/CarMark");
					System.out.println(realPath);
					File newFile=new File(realPath);
					if(!newFile.exists()){
						newFile.mkdirs();
					}
					try {
						FileUtils.copyFile(f,new File(newFile,fName));
					} catch (IOException e) {
						e.printStackTrace();
					}
					System.out.println("send file successful");
			}else{
				b=false;
			}
			return b;
		}
		public String fileExt(String fileName){
			String ext=fileName.substring(fileName.indexOf("."));
			return ext;
		}
}
